package com.jykj.modbus.equipment.service;

import java.util.HashMap;
import java.util.Map;

public class ThreadTest implements Runnable {
    //请求获得的数据
    public String reqDate = null;
    public boolean stoped = false;
    public static Map<String, ThreadTest> threadPool = new HashMap<String, ThreadTest>();//定义一个线程池

    public static void main(String[] args) {
        ThreadTest t = new ThreadTest();
        new Thread(t,"线程1").start();
        new Thread(t,"线程2").start();
        new Thread(t,"线程3").start();
        new Thread(t,"线程4").start();
        new Thread(t,"线程5").start();
        new Thread(t,"线程6").start();
        new Thread(t,"线程7").start();
        new Thread(t,"线程8").start();
        new Thread(t,"线程9").start();
        new Thread(t,"线程10").start();

        String resultDate = t.getReqDate();
        System.out.println("请求数据为："+resultDate);
    }

    //获得数据,没有数据则等待
    public synchronized String getReqDate(){
        try {
            if(reqDate == null){
                wait();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reqDate;
    }

    //如果其他线程都未获得数据，则把请求所得数据赋值给reqDate,并通知其它线程停止数据请求
    public synchronized void setReqDate(String date){
        if(reqDate == null){
            this.reqDate = date;
        }
        notifyAll();
    }

    @Override
    public void run() {
        try {
            for(int i = 0;i<30;i++){
                System.out.println(i+":  "+Thread.currentThread().getName()+"正在请求数据...."+reqDate);
                //如果已经获得数据，则不在发送请求
                if(stoped){
                    Thread.currentThread().interrupt();
                    break;
                }
                if(i == 18){
                    String date ="K9081";
                    System.out.println(i+":  "+Thread.currentThread().getName()+"已获得数据:"+date);
                    setReqDate(date);
                    stoped = true;
                    break;
                }

                Thread.sleep(1000);
            }
        } catch (Exception e) {
            System.out.println(Thread.currentThread().getName() + " interrupted.");
        }

    }
}
